<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.supplierName" placeholder="公司名" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.billTime"
              mode="month"
              :placeholder="['对账时间', '对账时间']"
            />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.sellers" placeholder="业务员" allow-clear />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="openEdit('新增')">新增</AButton>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="batchAdd()">批量新增</AButton>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        column-resizable
        size="small"
      >
        <template #columns>
          <ATableColumn title="客户名称" data-index="supplierName" :width="170"></ATableColumn>
          <ATableColumn title="采购单数" data-index="detailList" :width="90" align="center">
            <template #cell="{ record }">
              <div v-if="isEmpty(record.detailList)">0</div>
              <ALink v-else @click="rowEvent(record, 'open-bill')">
                {{ record.detailList.length }}
              </ALink>
            </template>
          </ATableColumn>
          <ATableColumn title="本期应付金额（含税）" data-index="curReceivableAmt" :width="120">
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.curReceivableAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="本期应付金额（不含税）"
            data-index="curReceivableExclTaxAmt"
            :width="120"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.curReceivableExclTaxAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="上期末剩余未收取（含税）"
            data-index="historyUnreceiveAmt"
            :width="150"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.historyUnreceiveAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="上期末剩余未收取（不含税）"
            data-index="historyUnreceiveExclTaxAmt"
            :width="150"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.historyUnreceiveExclTaxAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn title="本期已付金额（含税）" data-index="curReceivedAmt" :width="120">
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.curReceivedAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="本期已付金额（不含税）"
            data-index="curReceivedExclTaxAmt"
            :width="120"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.curReceivedExclTaxAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn title="核销金额" data-index="writeAmt" :width="90">
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.writeAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="本期末累计未收取（含税）"
            data-index="remainReceivableAmt"
            :width="120"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.remainReceivableAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn
            title="本期末累计未收取（不含税）"
            data-index="remainReceivableExclTaxAmt"
            :width="120"
          >
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.remainReceivableExclTaxAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn title="对账开始时间" data-index="" :width="120">
            <template #cell="{ record }">
              <div v-if="record.billStartDate">
                {{ `${dayjs(record.billStartDate).format('YYYY-MM-DD')}` }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="对账结束时间" data-index="" :width="120">
            <template #cell="{ record }">
              <div v-if="record.billEndDate">
                {{ `${dayjs(record.billEndDate).format('YYYY-MM-DD')}` }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="业务员" data-index="sellersName" :width="100" align="center">
          </ATableColumn>
          <ATableColumn title="对账情况" data-index="billDesc" :width="100" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill
                v-if="record.billDesc && record.supplierName !== '汇总'"
                style="color: #67c23a"
                size="20px"
              />
              <icon-close-circle-fill
                v-if="!record.billDesc && record.supplierName !== '汇总'"
                style="color: red"
                size="20px"
              />
            </template>
          </ATableColumn>
          <ATableColumn title="附件" data-index="createdDt" :width="160" align="center">
            <template #cell="{ record }">
              <ADropdown
                v-if="!isEmpty(record.fileList)"
                @select="(fileUrl: any) => openFlie(record, fileUrl)"
              >
                <ALink>{{ record.fileList.length }}</ALink>
                <template #content>
                  <ADoption
                    v-for="(item, index) in record.fileList"
                    :key="index"
                    :value="item.fileUrl"
                  >
                    {{ item.fileName }}
                  </ADoption>
                </template>
              </ADropdown>
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="160" align="center">
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 3])" title="操作" :width="145" fixed="right">
            <template #cell="{ record }">
              <ASpace v-if="record.supplierName !== '汇总'">
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
              <ASpace v-if="record.supplierName !== '汇总'" class="erp-mt-6">
                <AButton type="primary" size="mini" @click="rowEvent(record, 'print')">
                  打印
                </AButton>
                <AButton type="outline" size="mini" @click="rowEvent(record, 'export')">
                  导出
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="getTableData"
    >
    </EditPopupForm>
    <PayablePrint ref="payablePrintRef" :check-data="detailData"></PayablePrint>
    <!-- 采购单 -->
    <AModal
      v-model:visible="purchaseBillShow"
      title="采购单"
      width="800px"
      :body-style="{ padding: '0px' }"
      :footer="false"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <ATable
          :pagination="false"
          :data="purchaseBills"
          :bordered="{ cell: true }"
          column-resizable
          :span-method="spanMethod"
          size="small"
          :loading="purchaseBillLoad"
        >
          <template #columns>
            <ATableColumn title="采购单号" data-index="purchaseOrderCode" :width="100">
            </ATableColumn>
            <ATableColumn title="供应商" data-index="supplierName" :width="100"></ATableColumn>
            <ATableColumn title="产品名称" data-index="productName" :width="100"></ATableColumn>
            <ATableColumn title="规格型号" data-index="specModel" :width="100"></ATableColumn>
            <ATableColumn title="单位" data-index="unit" :width="100"></ATableColumn>
            <ATableColumn title="数量" data-index="qty" :width="100"></ATableColumn>
            <ATableColumn title="单价" data-index="unitPrice" :width="100"></ATableColumn>
            <ATableColumn title="金额" data-index="amt" :width="100">
              <template #cell="{ record }">
                {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
              </template>
            </ATableColumn>
            <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
              <template #cell="{ record }">
                <icon-check-circle-fill
                  v-if="record.isInclTax"
                  style="color: #67c23a"
                  size="20px"
                />
                <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
              </template>
            </ATableColumn>
            <ATableColumn title="交货日期" data-index="deliveryDate" :width="120">
              <template #cell="{ record }">
                <div v-if="record.deliveryDate">
                  {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
                </div>
              </template>
            </ATableColumn>
          </template>
        </ATable>
      </AScrollbar>
    </AModal>

    <!-- 批量新增 -->
    <AModal
      v-model:visible="batchAddShow"
      title="批量新增"
      :ok-loading="false"
      @close="modalEvent('close')"
      @before-ok="(done) => modalEvent('ok', done)"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="batchFormRef" :model="batchForm" auto-label-width>
        <AFormItem
          field="billEndDate"
          label="截止时间"
          :rules="[{ required: true, message: '请选择截止时间' }]"
          :validate-trigger="['change', 'input', 'blur']"
        >
          <ADatePicker
            v-model="batchForm.billEndDate"
            class="w100"
            placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import PayablePrint from './print.vue'
import dayjs from 'dayjs'
import { Message, Modal } from '@arco-design/web-vue'
import { downloadByteFile, formatPrice, decimalRound } from '@renderer/utils/mixins'
import { isAuth } from '@renderer/utils/auth'
import {
  AccountsListSearch,
  AccountsResItem,
  AccountsResItemDetailList,
  batchAddAccounts,
  BatchAddType,
  delAccounts,
  getAccountsAllList,
  getAccountsDetail,
  getAccountsPageList
} from '@renderer/api/statement'
import { isEmpty } from 'lodash-es'
import { useMenuState } from '@renderer/store'

const searchFrom = ref<AccountsListSearch>({
  customerName: '',
  supplierName: '',
  sellers: '',
  createdStartDate: '',
  createdEndDate: '',
  billType: 1,
  createTime: [],
  billTime: []
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<AccountsResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const payablePrintRef = ref<InstanceType<typeof PayablePrint>>()
const detailData = ref<AccountsResItem>({
  billId: '',
  customerName: '',
  customerId: '',
  curReceivableAmt: 0,
  historyUnreceiveAmt: 0,
  curReceivedAmt: 0,
  writeAmt: 0,
  remainReceivableAmt: 0,
  sellers: '',
  billDesc: '',
  billType: 1,
  remark: '',
  detailList: [],
  batchCount: 0,
  createdDt: '',
  billTime: [],
  billStartDate: '',
  billEndDate: '',
  curReceivableExclTaxAmt: 0,
  historyUnreceiveExclTaxAmt: 0,
  curReceivedExclTaxAmt: 0,
  remainReceivableExclTaxAmt: 0,
  purchaseNum: 0
}) // 打印数据
const purchaseBillShow = ref(false)
const purchaseBillLoad = ref(false)
const purchaseBills = ref<AccountsResItemDetailList[]>([])
const batchAddShow = ref(false)
const batchForm = ref<BatchAddType>({
  billEndDate: '',
  billType: 1
})
const batchFormRef = ref()
const menuParam = useMenuState()

onMounted(() => {
  getTableData()
})

async function getTableData() {
  const [billStartDate, billEndDate] = searchFrom.value.billTime! || []
  searchFrom.value.billStartDate = billStartDate ? dayjs(billStartDate).format('YYYY-MM-DD') : ''
  searchFrom.value.billEndDate = billEndDate ? dayjs(billEndDate).format('YYYY-MM-DD') : ''
  const res = await getAccountsPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  // tableData.value.splice(0, 1)
  pageParam.totalCount = res.data.totalCount!
}

function onSearch() {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {
    customerName: '',
    sellers: '',
    createdStartDate: '',
    createdEndDate: '',
    billType: 1,
    billTime: []
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {
    purchaseNum: 0,
    billId: '',
    customerId: '',
    curReceivableAmt: 0,
    curReceivableExclTaxAmt: 0,
    historyUnreceiveAmt: 0,
    curReceivedAmt: 0,
    writeAmt: 0,
    remainReceivableAmt: 0,
    sellers: '',
    billDesc: '',
    billType: 1,
    remark: '',
    detailList: [],
    batchCount: 0,
    createdDt: '',
    billTime: [],
    billStartDate: '',
    billEndDate: '',
    historyUnreceiveExclTaxAmt: 0,
    curReceivedExclTaxAmt: 0,
    remainReceivableExclTaxAmt: 0
  }
  editModalTitle.value = title
  editModal.value = true
}

function formatData(baseData: any[]): any[] {
  return baseData
    .map((item, index) => {
      item.index = index + 1
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return { ...item, span: item.detailList.length, ...detailItem }
          } else {
            return { ...item, ...detailItem }
          }
        })
      } else {
        return [item]
      }
    })
    .flat()
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 2 || columnIndex > 7) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

const rowData = ref<AccountsResItem>()

function rowEvent(row: AccountsResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delAccounts({ billId: row.billId }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      getAccountsDetail({ billId: row.billId }).then((res) => {
        detailData.value = res.data
        detailData.value.supplierName = row.supplierName
        nextTick(() => {
          payablePrintRef.value?.printInfo()
        })
      })
      break
    case 'open-bill':
      purchaseBillShow.value = true
      purchaseBillLoad.value = true
      getAccountsDetail({ billId: row.billId }).then((res) => {
        purchaseBills.value = formatData(res.data.detailList || [])
        purchaseBillLoad.value = false
      })
      break
    case 'export':
      getAccountsDetail({ billId: row.billId }).then((res) => {
        import('./export').then((excel) => {
          const StartDate = `${dayjs(row.billStartDate).format('YYYY-MM-DD')}`
          const EndDate = `${dayjs(row.billEndDate).format('YYYY-MM-DD')}`
          excel.exportExcel(
            { ...res.data, supplierName: row.supplierName },
            `${row.supplierName}-${StartDate}~${EndDate} 应付账款`
          )
        })
      })
      break
    default:
      break
  }
}

const openFlie = (record: AccountsResItem, flieUrl: string) => {
  const temp = record.fileList?.find((item) => item.fileUrl === flieUrl)
  if (temp) {
    downloadByteFile(temp)
  }
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '客户名称', value: 'supplierName', width: 180 },
    { title: '采购单数', value: 'purchaseNum', width: 180 },
    { title: '本期应付金额（含税）', value: 'curReceivableAmt' },
    { title: '本期应付金额（不含税）', value: 'curReceivableExclTaxAmt' },
    { title: '上期末剩余未收取（含税）', value: 'historyUnreceiveAmt' },
    { title: '上期末剩余未收取（不含税）', value: 'historyUnreceiveExclTaxAmt' },
    { title: '本期已付金额（含税）', value: 'curReceivedAmt' },
    { title: '本期已付金额（不含税）', value: 'curReceivedExclTaxAmt' },
    { title: '核销金额', value: 'writeAmt' },
    { title: '本期末累计未收取（含税）', value: 'remainReceivableAmt', width: 180 },
    { title: '本期末累计未收取（不含税）', value: 'remainReceivableExclTaxAmt', width: 180 },
    { title: '业务员', value: 'sellersName' },
    { title: '对账情况', value: 'billDesc' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: AccountsResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '应付账款数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getAccountsAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.purchaseNum = item.batchCount
          item.index = index + 1
          return item
        })
      }
      break

    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}

function batchAdd() {
  batchAddShow.value = true
}

// 批量新增弹窗事件
function modalEvent(type: string, done?: (closed: boolean) => void) {
  switch (type) {
    case 'ok':
      batchFormRef.value.validate((errors) => {
        if (!errors) {
          batchForm.value.billType = 1
          batchAddAccounts(batchForm.value)
            .then(() => {
              Message.success('批量新增成功')
              modalEvent('cancel')
              done!(true)
              onSearch()
            })
            .catch(() => {
              done!(false)
            })
        } else {
          done!(false)
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      batchFormRef.value.resetFields()
      batchAddShow.value = false
      break
    case 'open':
      menuParam.switchEditStatus(true)
      break
    case 'cancel':
      batchFormRef.value.resetFields()
      menuParam.switchEditStatus(false)
      batchAddShow.value = false
      break
    default:
      break
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
